package com.screen.screendisplay.service.impl.coal;

import com.screen.screendisplay.entity.coal.CoalSafetyenvAlarm;
import com.screen.screendisplay.mapper.coal.CoalSafetyenvAlarmMapper;
import com.screen.screendisplay.service.coal.CoalSafetyenvAlarmService;
import com.screen.screendisplay.vo.coal.CoalSafetyAlertVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 安全环保告警表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class CoalSafetyenvAlarmServiceImpl extends ServiceImpl<CoalSafetyenvAlarmMapper, CoalSafetyenvAlarm> implements CoalSafetyenvAlarmService {

    @Override
    public List<CoalSafetyAlertVO> getSafetyAlerts(Integer year) {
        // 查询条件
        QueryWrapper<CoalSafetyenvAlarm> queryWrapper = new QueryWrapper<>();
        
        // 如果指定了年份，按年份过滤
        if (year != null) {
            queryWrapper.eq("year", year);
        } else {
            // 默认获取最近的告警数据（比如最近一个月的数据）
            LocalDateTime oneMonthAgo = LocalDateTime.now().minusMonths(1);
            queryWrapper.ge("alarm_time", oneMonthAgo);
        }
        
        // 按告警时间倒序排列，获取最新的告警数据
        queryWrapper.orderByDesc("alarm_time");
        
        // 限制返回数量（比如最多返回10条）
        queryWrapper.last("LIMIT 10");
        
        List<CoalSafetyenvAlarm> alarmList = this.list(queryWrapper);
        
        // 转换为VO对象
        return alarmList.stream().map(entity -> {
            CoalSafetyAlertVO vo = new CoalSafetyAlertVO();
            vo.setAlarmType(entity.getAlarmType());
            vo.setUnitCode(entity.getUnitCode());
            vo.setUnitName(entity.getUnitName());
            vo.setAlarmTime(entity.getAlarmTime());
            vo.setAlarmInfo(entity.getAlarmInfo());
            vo.setConfirmStatus(entity.getConfirmStatus());
            return vo;
        }).collect(Collectors.toList());
    }

}
